﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Media;
using System.Windows.Shapes;
using SpectrumAnalyser.ModelObjects;
using SpectrumAnalyser.Common.Extensions;

namespace SpectrumAnalyser.Controls.Wpf.Virtualization.Elements
{
    public class VirtualPath:IVirtualChild
    {
        private IList<SpectrumPoint> _points;
        private Brush _brush;
        private UIElement _visual;

        public VirtualPath(IList<SpectrumPoint> points, Brush brush)
        {
            _points = points;
            _brush = brush;
            Bounds = new Rect(0, 0, Math.Abs(_points.MinBy(x => x.X).X - _points.MaxBy(x => x.X).X),
                              Math.Abs(_points.MinBy(x => x.Y).Y - _points.MaxBy(x => x.Y).Y));
        }

        public Rect Bounds { get; private set; }
        public event EventHandler BoundsChanged;
        public UIElement Visual { get; private set; }
        public UIElement CreateVisual(VirtualCanvas parent)
        {
            if (_visual == null)
            {
                _visual = new Path()
                              {
                                  Stroke = _brush,
                                  Data =
                                      CreatePathFigureCollection(new Point(_points[0].X, _points[0].Y),
                                                                 GetBezierSegments(_points))
                              };
            }

            return _visual;
        }

        public void DisposeVisual()
        {
            _visual = null;
        }

        private PathSegmentCollection GetBezierSegments(IEnumerable<SpectrumPoint> points)
        {
            var pathSegmentCollection = new PathSegmentCollection();

            foreach (SpectrumPoint point in points)
            {
                pathSegmentCollection.Add(new LineSegment
                {
                    Point = new Point((double)point.X, (double)point.Y),
                    IsSmoothJoin = true
                });
            }

            return pathSegmentCollection;
        }

        private PathGeometry CreatePathFigureCollection(Point startPoint, PathSegmentCollection collection)
        {
            return new PathGeometry
            {
                Figures = new PathFigureCollection
                                              {
                                                  new PathFigure
                                                      {
                                                          StartPoint = startPoint,
                                                          Segments = collection
                                                      }
                                              }
            };
        }
    }
}